package com.zrb.mobile.ui;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import com.hhpm.lib.xlist.PullToRefreshListFooter;
import com.hhpm.lib.xlist.PullToRefreshSwipeMenuListView;
import com.hhpm.lib.xlist.PullToRefreshSwipeMenuListView.IXListViewListener;
import com.zrb.mobile.utility.CommonUtil;

public class PullToRefreshSwipeMenuListViewEx extends PullToRefreshSwipeMenuListView {

	int pagesize=10;
	ListAdapter mBaseAdapter;	
	PullToRefreshListFooter mloadingview; 
	boolean isLoading=false;
	IXListViewListener monLoadMoreListener;
	private boolean mLastItemVisible;
	boolean canloadmore=true;
	
	public PullToRefreshSwipeMenuListViewEx(Context context) {
		super(context);
		initFoot();
	}

	public PullToRefreshSwipeMenuListViewEx(Context context,
			AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initFoot();

	}

	public PullToRefreshSwipeMenuListViewEx(Context context, AttributeSet attrs) {
		super(context, attrs);
		initFoot();

	}
	
	private void initFoot(){
		
		mloadingview= super.getFootView();
		
	}
 
 
	
	public void setPagesize(int curPagesize){
		pagesize=curPagesize;
	}

	public void initAdapter(ListAdapter madapter){
		mBaseAdapter=madapter;
		this.setAdapter(madapter);
	}
	
	
	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
 
		  if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && null != getXListViewListener() && mLastItemVisible) {
				//mOnLastItemVisibleListener.onLastItemVisible();
		 
				 onLastItemVisible();
		  }
	      super.onScrollStateChanged(view, scrollState);
	}

	
	 @Override
	 public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
	        // send to user's listener
	    	if (null != getXListViewListener()) {
 				mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
			}
	     
	    	 super.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
	}
	
	 private void onLastItemVisible(){
			
		    if(!canloadmore) return;
	    	if(mBaseAdapter.getCount()<pagesize) return;
			if(isLoading) return;

			isLoading=true;
		
			mloadingview.show();
 			mloadingview.setState(PullToRefreshListFooter.STATE_LOADING);
 			super.setSelection(mBaseAdapter.getCount()-1);
			if(null != getXListViewListener()) getXListViewListener().onLoadMore();
	 } 
	    
	 

		public void hideloading(){
			isLoading=false;
		 	mloadingview.setState(PullToRefreshListFooter.STATE_NORMAL);
		}
		
		public void checkloadMore(int size){
	 		if(size<pagesize) canloadmore=false;;
		}
		
		// public void set  onRefreshComplete
		public void setRefreshComplete(){
			canloadmore=true;
			super.stopRefresh();
		}  
		
}
